$(function () {
    findAll();
})

//设置查询出来的信息数据
function setData(data) {
    let html = '';
    for (let i = 0; i < data.length; i++) {
        html += ' <div>\n' +
            '            <div style="width: 50px">' + data[i].id + '</div>\n' +
            '            <div style="width: 150px">' + data[i].username + '</div>\n' +
            '            <div style="width: 150px">' + data[i].phone + '</div>\n' +
            '            <div style="width: 100px">' + data[i].sex + '</div>\n' +
            '            <div style="width: 250px">' + data[i].hobby + '</div>\n' +
            '            <div style="width: 250px">' + data[i].introduce + '</div>\n' +
            '            <div style="width: 250px">' + data[i].birthday + '</div>\n' +
            '            <div class="operator">\n' +
            '                <div><input type="button" value="编辑" onclick="edit(' + data[i].id + ')"></div>\n' +
            '                <div><input type="button" value="删除" onclick="del(' + data[i].id + ')"> </div>\n' +
            '            </div>\n' +
            '        </div>';
    }
    //delete from user where id=4
    $("#content").html(html);
}

function edit(id) {
    localStorage.setItem("userId", id);
    // sessionStorage.setItem("userId", id);
    // $.cookie("userId", id);
    $('#right').load('/html/back/user/userUpdate.html');
}

function del(id) {
    $.ajax({
        url: '/back/user/del',
        data: {id: id},//key  value
        type: 'post',//所有新增，删除，修改全部用post，查询全部用get
        dataType: 'json',//后台传递给前端的数据类型
        success: function (data) {
            if (data.result == 1) {
                findAll();
            } else {
                alert("删除失败!")
            }
        }
    })
}

function addUser() {
    $('#right').load('/html/back/user/userRegiter.html');
}

function findAll() {
    let data = {
        username: $("#username").val(),
        phone: $("#phone").val(),
        sex: $("#sex").val(),
        hobby: JSON.stringify(aihao()),
        startBirthday: $("#startBirthday").val(),
        endBirthday: $("#endBirthday").val(),
    };
    let resultData = myAjax("/back/user/findAll", data, "get");
    resultData = resultData.list;
    setData(resultData);
}

function aihao() {
    let hb = [];
    $("input:checkbox[name='hobby']").each(function () {
        if ($(this).prop("checked")) {
            hb.push($(this).val());
        }
    })
    return hb;
}